package net.semanticmetadata.seams;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.awt.image.BufferedImage;

/*
 * This file is part of SeamCarving.
 *
 * SeamCarving is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Caliph & Emir is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Caliph & Emir; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Copyright statement:
 * ********************
 * (c) 2007 by Mathias Lux (mathias@juggle.at)
 * Palmengasse 20, 8010 Graz, Austria
 * http://www.semanticmetadata.net
 */
public class SeamCarving {
    public static void main(String[] args) {
        String inputFile = null;
        BufferedImage inFile = null;
        String outputFile = null;
        int newWidth = -1;
        int newHeight = -1;
        int reduceHeight = -1;
        int reduceWidth = -1;
        int h = 0, w = 0;
        if (args.length < 2) {
            showHelp();
        }
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-i")) {
                inputFile = args[i + 1];
            } else if (args[i].equals("-nh")) {
                newHeight = getInt(args[i + 1]);
            } else if (args[i].equals("-nw")) {
                newWidth = getInt(args[i + 1]);
            } else if (args[i].equals("-rh")) {
                reduceHeight = getInt(args[i + 1]);
            } else if (args[i].equals("-rw")) {
                reduceWidth = getInt(args[i + 1]);
            } else if (args[i].equals("-?") || args[i].endsWith("-help")) {
                showHelp();
            } else if (args[i].equals("-o")) {
                outputFile = args[i + 1];
            }
        }

        if (inputFile == null) {
            System.err.println("No input file given!");
            showHelp();
        } else {
            try {
                inFile = ImageIO.read(new FileInputStream(inputFile));
                h = inFile.getHeight();
                w = inFile.getWidth();
            } catch (IOException e) {
                System.err.println(e);
                showHelp();
            }
        }

        if (newHeight == -1 && newWidth == -1 && reduceWidth == -1 && reduceHeight == -1) {
            System.out.println("Image width: " + w);
            System.out.println("Image height: " + h);
            System.err.println("At least one parameter for image retargeting must be given!\n" +
                    "Use parameter -help to show help.");
            showHelp();
        }

        if (newHeight > -1 && reduceHeight == -1) {
            reduceHeight = h - newHeight;
        }
        if (newWidth > -1 && reduceWidth == -1) {
            reduceWidth = w - newWidth;
        }

        if (reduceWidth == -1) reduceWidth = 0;
        if (reduceHeight == -1) reduceHeight = 0;

        if (reduceWidth > w || reduceWidth < 0) {
            System.out.println("New width not appropriate. Only reduction is possible.");
            System.out.println("\tImage width: " + w);
            System.out.println("\tImage height: " + h);
            System.exit(0);
        }

        if (reduceHeight > h || reduceHeight < 0) {
            System.out.println("New width not appropriate. Only reduction is possible.");
            System.out.println("\tImage width: " + w);
            System.out.println("\tImage height: " + h);
            System.exit(0);
        }

        ImageSeamOperations s = new ImageSeamOperations(inFile);
        int steps = Math.max(reduceWidth, reduceHeight);
        System.out.println("Processing image. Please wait ...");
        for (int k = 0; k < steps; k++) {
            if (reduceHeight > 0) {
                s.carveHorizontalSeam();
                reduceHeight--;
            }
            if (reduceWidth > 0) {
                s.carveVerticalSeam();
                reduceWidth--;
            }
        }
        // write out the file.
        try {
            if (outputFile == null) {
                String in = new File(inputFile).getCanonicalPath();
                outputFile = in.substring(0, in.lastIndexOf('.')) + "_carved.png";
            }
            System.out.println("Finished. Writing output to " + outputFile);
            File oFile = new File(outputFile);
            ImageIO.write(s.getImg(), "png", oFile);
        } catch (IOException e) {
            System.err.println("Could not write result to disk.");
            e.printStackTrace();
        }

    }

    private static int getInt(String str) {
        int result = 0;
        try {
            result = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            System.err.println("Error: " + str + " is not a number.");
            showHelp();
        }
        return result;
    }

    /**
     * Show help and exit.
     */
    public static void showHelp() {
        String help = "SeamCarving -i <infile> [-o <outfile>] [-nh <int>] [-nw <int>] [-rh <int>] [-rw <int>]\n" +
                "\t-i  ... infile jas to be an image (jpg or png)\n" +
                "\t-o  ... optional outfile, has to be png, \n" +
                "\t        if none given a new one is created\n" +
                "\t-nh ... new image height after carving operation\n" +
                "\t-nw ... new image width after carving operation\n" +
                "\t-rh ... reduce image in height by this number\n" +
                "\t-rw ... reduce image in width by this number\n" +
                "\t\n" +
                "Example usage:\n" +
                "\tSeamCarving -i photo.jpg -rh 200 -rw 300\n" +
                "\t\treduces inputfile by 200 in height and by 300 in width\n" +
                "\t\toutputs to photo_carved.png\n" +
                "\tSeamCarving -i photo.jpg -nh 200 -nw 300\n" +
                "\t\treduces inputfile to size 300x200";
        System.out.println(help);
        System.exit(0);
    }
}
